package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.FightReport;
import pl.un4giv3n.mightvsmagic.entity.ItemStub;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.FightUtil;
import pl.un4giv3n.mightvsmagic.utils.FormatterUtil;

/**
 * @author andrzejewskia
 * show selected fight report
 */
public class ShowFightReportAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * fight result
	 */
	private FightReport fight;
	/**
	 * selected fight id
	 */
	private long fightId;
	/**
	 * list of defender items
	 */
	private List<ItemStub> defenderItems;
	/**
	 * list of attacer items
	 */
	private List<ItemStub> attackerItems;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		fight = entityManager.find(FightReport.class, fightId);
		if(fight.isClanWarReport() || user.getId().longValue() == fight.getAttacker().getUserId().longValue() ||
				user.getId().longValue() == fight.getDefender().getUserId().longValue() || user.getUserType() == UserType.ADMIN){
			defenderItems = fight.getDefender().getItems();
			attackerItems = fight.getAttacker().getItems();
			//BAD BAD HACK AROUND LAZY INIT LOADING...
			for (ItemStub stub : defenderItems) {
				stub.getId();
			}
			for (ItemStub stub : attackerItems) {
				stub.getId();
			}
			if(user.getLogin().equals(fight.getDefenderLogin()) && !fight.isDefenderSeen()){
				EntityTransaction transaction = entityManager.getTransaction();
				transaction.begin();
				fight.setDefenderSeen(true);
				entityManager.merge(fight);
				entityManager.flush();
				transaction.commit();
			}
			entityManager.close();
			return SUCCESS;
		}else{
			addActionError("Nie masz uprawnień do przeglądania tego raportu.");
			entityManager.close();
			return ERROR;
		}
	}

	// this is the data for page fight-report.jsp

	public FightReport getFight() {
		return fight;
	}

	public String getAttackerDamage() {
		return FormatterUtil.formatDamage(FightUtil.getAttackerDamage(fight));
	}

	public String getDefenderDamage() {
		return FormatterUtil.formatDamage(FightUtil.getDefenderDamage(fight));
	}
	public List<ItemStub> getDefenderEquipedItems(){
		return defenderItems;
	}
	public List<ItemStub> getAttackerEquipedItems(){
		return attackerItems;
	}

	public long getFightId() {
		return fightId;
	}

	public void setFightId(long fightId) {
		this.fightId = fightId;
	}

}
